package util

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"fmt"
)

import (
	"crypto/rand"
	"errors"
)

const (
	version    = 0x01 // 密钥版本号
	keyLen     = 32   // AES-256密钥长度
	ivLen      = 16   // IV长度
	blockSize  = 16   // AES块大小
	versionLen = 1    // 版本号长度
)

// EncryptBytes 加密字节数据，密钥长度32字节
func EncryptBytes(plaintext, key []byte) (string, error) {
	// 验证密钥长度
	if len(key) != keyLen {
		return "", fmt.Errorf("invalid key length: expected %d, got %d", keyLen, len(key))
	}

	// 生成随机IV
	iv := make([]byte, ivLen)
	if _, err := rand.Read(iv); err != nil {
		return "", fmt.Errorf("failed to generate IV: %v", err)
	}

	// 填充明文
	paddedPlaintext := PKCS7Pad(plaintext, blockSize)

	// 创建加密块
	block, err := aes.NewCipher(key)
	if err != nil {
		return "", fmt.Errorf("failed to create cipher: %w", err)
	}

	// 创建CBC加密器
	ciphertext := make([]byte, len(paddedPlaintext))
	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(ciphertext, paddedPlaintext)

	// 组合版本号+IV+密文
	result := make([]byte, 0, versionLen+ivLen+len(ciphertext))
	result = append(result, version)
	result = append(result, iv...)
	result = append(result, ciphertext...)

	// Base64编码
	return base64.StdEncoding.EncodeToString(result), nil
}

// EncryptString 加密字符串数据，密钥长度32字节
func EncryptString(plaintext string, key []byte) (string, error) {
	return EncryptBytes([]byte(plaintext), key)
}

// DecryptBytes 解密字节数据，密钥长度32字节
func DecryptBytes(ciphertext string, key []byte) ([]byte, error) {
	// 验证密钥长度
	if len(key) != keyLen {
		return nil, fmt.Errorf("invalid key length: expected %d, got %d", keyLen, len(key))
	}

	// Base64解码
	raw, err := base64.StdEncoding.DecodeString(ciphertext)
	if err != nil {
		return nil, fmt.Errorf("base64 decode failed: %w", err)
	}

	// 验证最小长度
	minLen := versionLen + ivLen + blockSize
	if len(raw) < minLen {
		return nil, fmt.Errorf("invalid ciphertext length: minimum %d, got %d", minLen, len(raw))
	}

	// 解析版本号
	if raw[0] != version {
		return nil, fmt.Errorf("unsupported version: %d", raw[0])
	}

	// 提取IV和密文
	iv := raw[versionLen : versionLen+ivLen]
	encryptedData := raw[versionLen+ivLen:]

	// 创建解密块
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, fmt.Errorf("cipher creation failed: %w", err)
	}

	// 验证密文长度
	if len(encryptedData)%blockSize != 0 {
		return nil, fmt.Errorf("invalid ciphertext length: not multiple of block size")
	}

	// 创建CBC解密器
	mode := cipher.NewCBCDecrypter(block, iv)
	decrypted := make([]byte, len(encryptedData))
	mode.CryptBlocks(decrypted, encryptedData)

	// 去除填充
	return PKCS7UnPad(decrypted, blockSize)
}

// DecryptString 解密字符串数据，密钥长度32字节
func DecryptString(ciphertext string, key []byte) (string, error) {
	decryptedBytes, err := DecryptBytes(ciphertext, key)
	if err != nil {
		return "", err
	}
	return string(decryptedBytes), nil
}

// PKCS7Pad PKCS#7填充实现
func PKCS7Pad(data []byte, blockSize int) []byte {
	padding := blockSize - (len(data) % blockSize)
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(data, padText...)
}

// PKCS7UnPad PKCS#7去除填充
func PKCS7UnPad(data []byte, blockSize int) ([]byte, error) {
	length := len(data)
	if length == 0 {
		return nil, errors.New("empty input")
	}

	if len(data)%blockSize != 0 {
		return nil, errors.New("invalid padded data length")
	}

	padding := int(data[length-1])
	if padding < 1 || padding > blockSize {
		return nil, errors.New("invalid padding value")
	}

	if length < padding {
		return nil, errors.New("padding exceeds data length")
	}

	// 验证填充字节是否正确
	for i := 0; i < padding; i++ {
		if data[length-padding+i] != byte(padding) {
			return nil, errors.New("invalid padding bytes")
		}
	}

	return data[:length-padding], nil
}
